<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { updateEmp, queryDetail } from "@/api/emp.js";
import { ElMessage } from "element-plus";
import { getDeptList } from "@/api/dept.js";
import { getRoleList } from "@/api/role.js";
import { checkUser } from "@/api/sysuser.js";
const router = useRouter();
//路由信息
const route = useRoute();
//表单数据
const addForm = ref(null);
//员工数据
const emp = ref({
  account: "",
  annual_target: "",
  birthday: "",
  contact_info: "",
  department_id: "",
  e_name: "",
  hire_date: "",
  isaudit: 1,
  password: "",
  position: "",
  role_id: "",
  type: 1,
  base_salary: ""
});
//部门数据
const dept = ref([]);
//角色数据
const role = ref([]);
//生命周期
onMounted(() => {
  initData();
  console.log("route:", route);
  let employee_id = route.query.employee_id;
  queryDel(employee_id);
});
//部门数据转换
function transformDeptData1(data) {
  return data.map(item => ({
    value: item.dept_id,
    label: item.dept_name,
    children: item.children ? transformDeptData1(item.children) : []
  }));
}
function transformDeptData2(data) {
  return data.map(item => ({
    value: item.role_id,
    label: item.role_name
  }));
}
async function initData() {
  try {
    let res = await getDeptList(0);
    if (res.code === 200) {
      dept.value = transformDeptData1(res.data);
    } else {
      console.error("获取部门数据失败:", res.message);
    }
  } catch (error) {
    console.error("请求部门数据时出错:", error);
  }
  try {
    let rs = await getRoleList();
    if (rs.code === 200) {
      role.value = transformDeptData2(rs.data);
    } else {
      console.error("获取角色数据失败:", rs.message);
    }
  } catch (error) {
    console.error("请求角色数据时出错:", error);
  }
}

//表单校验
const rules = {
  department_id: [
    { required: true, message: "请输入所属部门！", trigger: "blur" }
  ],
  role_id: [{ required: true, message: "请输入角色！", trigger: "blur" }],
  type: [{ required: true, message: "请输入类型！", trigger: "blur" }]
};
//取消按钮
function resetForm() {
  router.push("/emp/list");
}

const handleDepartmentChange = selectedDepartmentId => {
  emp.value.department_id = selectedDepartmentId;
  console.log("Selected Department ID:", emp.value.mpdepartment_id);
};
//检测账号是否存在
async function chk() {
  if (emp.value.account == "") {
    ElMessage({
      message: "账号不能为空！",
      type: "warning"
    });
    return;
    //程序返回false，不执行后续代码
  }
  //调用接口，检测账号是否重复
  let res = await checkUser(emp.value.account);
  if (res.code == 200) {
    if (res.data == "yes") {
      ElMessage({
        message: "该账号已存在！",
        type: "warning"
      });
    }
  }
}
//查询详情
async function queryDel(id) {
  let res = await queryDetail(id);
  if (res.code === 200) {
    console.log("emp:", res.data);
    emp.value = res.data;
  }
}
//修改数据
async function upDateEmp() {
  let res = await updateEmp(emp.value);
  if (res.code === 200) {
    ElMessage({
      message: "修改成功",
      type: "success"
    });
    resetForm();
  }
}
</script>
<template>
  <div
    style="
      width: 80%;
      margin: 40px auto;
      background-color: #fff;
      border: black solid 1px;
    "
  >
    <!-- 头部div -->
    <div
      style="
        height: 50px;
        line-height: 50px;
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 10px;
        background-color: #efefef;
        border-bottom: black solid 1px;
      "
    >
      <i style="margin-left: 30px; margin-top: 10px">修改</i>
    </div>
    <!-- 表单 -->
    <el-form
      ref="addForm"
      :model="emp"
      :rules="rules"
      label-width="120px"
      style="padding-top: 10px; width: 90%; margin: auto"
    >
      <el-row>
        <el-col :span="12"
          ><el-form-item label="账号：" prop="account">
            <el-input
              v-model="emp.account"
              placeholder="请输入账号"
              readonly
              @blur="chk"
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="密码：" prop="password">
            <el-input
              v-model="emp.password"
              placeholder="请输入密码"
              disabled
            /> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="姓名：">
            <el-input
              v-model="emp.e_name"
              placeholder="请输入"
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="联系方式：">
            <el-input
              v-model="emp.contact_info"
              placeholder="请输入"
            /> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="所属部门：" prop="department_id">
            <el-tree-select
              v-model="emp.mpdepartment_id"
              :data="dept"
              :render-after-expand="false"
              style="width: 430px; margin-right: 0"
              @change="handleDepartmentChange"
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="职务：">
            <el-input
              v-model="emp.position"
              placeholder="请输入"
            /> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="底薪：">
            <el-input
              v-model="emp.base_salary"
              placeholder="请输入"
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="员工生日：">
            <el-date-picker
              v-model="emp.birthday"
              placeholder="请选择员工生日（月日）"
              format="MM-DD"
              value-format="MM-DD"
              style="width: 420px" /></el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="入职时间：">
            <div class="block">
              <el-date-picker
                v-model="emp.hire_date"
                type="date"
                placeholder="Pick a day"
                style="width: 400px"
              />
            </div> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="角色：" prop="role_id">
            <el-select
              v-model="emp.role_id"
              class="m-2"
              placeholder="请选择"
              style="width: 430px; margin-right: 0; margin-left: 0"
            >
              <el-option
                v-for="item in role"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型：" prop="type">
            <el-radio-group v-model="emp.type">
              <el-radio :value="1" size="large">普通员工</el-radio>
              <el-radio :value="2" size="large">内销</el-radio>
              <el-radio :value="3" size="large">外销</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品参数支持：">
            <el-radio-group v-model="emp.isaudit">
              <el-radio :value="1" size="large">需要审核</el-radio>
              <el-radio :value="2" size="large">无需审核</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="年度业绩目标：">
            <el-input
              v-model="emp.annual_target"
              placeholder="请输入"
            /> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
    <div style="margin-bottom: 20px; text-align: center">
      <el-button type="primary" style="margin-right: 100px" @click="upDateEmp"
        >保存</el-button
      >
      <el-button type="primary" @click="resetForm">取消</el-button>
    </div>
  </div>
</template>

<style lang="less" scoped></style>
